const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    emojiUrl:"https://xhzcx.com/wxfile/07tcn23y8q8lvw8ru3vp.png",
    emojiSize: 48, // 表情图片大小
    emojiMargin: 10, // 表情图片与文本之间的间距
    text: "", // 用于存储公告栏显示文本
    marqueePace: 1.3, // 滚动速度
    marqueeDistance: 0, // 初始滚动距离
    size: 28, // 字号
    marqueeWidth: 750, // 文本宽度
    intervalId: null, // 存储定时器的ID
    animationId: null, // 存储动画帧的ID
    feedback_list: [], // 待反馈活动列表

    newGoods: [],
    hotGoods: [],
    topics: [],
    brands: [],
    groupons: [],
    floorGoods: [],
    banner: [],
    channel: [],
    coupon: [],
    goodsCount: 0,
    initPage: false
  },

  onShareAppMessage: function() {
    return {
      title: '熊孩纸冲洗',
      desc: '小程序商城',
      path: '/pages/index/index'
    }
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getIndexData();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  getIndexData: function() {
    let that = this;
    util.request(api.IndexUrl).then(function(res) {
      if (res.errno === 0) {
        that.startMarquee(); // 启动滚动公告栏

        that.setData({
          newGoods: res.data.newGoodsList,
          hotGoods: res.data.hotGoodsList,
          topics: res.data.topicList,
          brands: res.data.brandList,
          floorGoods: res.data.floorGoodsList,
          banner: res.data.banner,
          groupons: res.data.grouponList,
          channel: res.data.channel,
          coupon: res.data.couponList,
          text: res.data.notice.title,
          initPage: true
        });
      }
    });
    util.request(api.GoodsCount).then(function (res) {
      that.setData({
        goodsCount: res.data
      });
    });
  },
  onLoad: async function(options) {
/*    console.log("options", options)
    try {
      const isLogin = await user.checkLogin()
      app.globalData.hasLogin = isLogin
    } catch (error) {}

    if (options.supid) {
      app.globalData.supid = options.supid
      if (!app.globalData.hasLogin) {
        wx.navigateTo({
          url: '/pages/auth/login/login'
        })
        return
      }
      if (options.supid) {
        this.bindSecondaryAgen(options.supid)
      }
    }*/
    // 页面初始化 options为页面跳转所带来的参数
    if (options.scene) {
      var scene = decodeURIComponent(options.scene);
      console.log("scene:" + scene);
      let info_arr = [];
      info_arr = scene.split(',');
      let _type = info_arr[0];//取出第一个商品参数
      if (_type == 'goods') {
        let id = info_arr[1];
        let supid = info_arr[2];
        app.globalData.supid = supid
        app.globalData.type = '1'//扫描商品码->成为普通用户
        if (!app.globalData.hasLogin) {
          wx.navigateTo({
            url: '/pages/auth/login/login'
          })
          return
        }
        this.bindSecondaryAgen(supid)
        wx.navigateTo({
          url: '../index/index'
        });
      }else if (_type == 'supid'){//扫描代理分享的码
        let supid = info_arr[1];
        app.globalData.supid = supid
        app.globalData.type = '2'//扫描代理分享的码->成为二级代理或者普通用户
        if (!app.globalData.hasLogin) {
          wx.navigateTo({
            url: '/pages/auth/login/login'
          })
          return
        }
        this.bindSecondaryAgen1(supid)
      }else{
        wx.navigateTo({
          url: '../index/index'
        });
      }
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.grouponId) {
      //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?grouponId=' + options.grouponId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.goodId) {
      //这个goodId的值存在则证明首页的开启来源于分享,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?id=' + options.goodId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.orderId) {
      //这个orderId的值存在则证明首页的开启来源于订单模版通知,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../ucenter/orderDetail/orderDetail?id=' + options.orderId
      });
    }

    this.getIndexData();
  },

  onShow: function() {
    // 页面显示
    let that = this
    if (!that.data.intervalId) { // 若不存在定时器，创建定时器
      that.startMarquee();
    }
    if (this.data.initPage) {
      this.getIndexData();
    }
  },
  // 绑定申请成为二级代理
  bindSecondaryAgen(supid) {
    util.request(api.SecondaryAgenApi, {
      supid: Number(supid)
    }, 'GET').then(res => {
      if (res.errno === 0) {
        wx.showToast({
          title: res.errmsg
        })
      }
      else{
        util.showErrorToast(res.errmsg);
      }
    })
  },
  // 成为代理下的用户
  bindSecondaryAgen1(supid) {
    util.request(api.SecondaryAgenApi1, {
      supid: Number(supid)
    }, 'GET').then(res => {
      if (res.errno === 0) {
        wx.showToast({
          title: res.errmsg
        })
      }else{
        util.showErrorToast(res.errmsg);
      }
    })
  },
  startMarquee: function () {
    this.clearMarqueeInterval();
    const length = this.data.text.length * this.data.size; // 计算文本长度
    const width = this.data.marqueeWidth;
    // 保留初始设置
    this.setData({
      marqueeDistance: width
    });

    const pace = this.data.marqueePace;

    this.data.intervalId = setInterval(() => {
      let distance = this.data.marqueeDistance - pace;
      // 确保整个文本长度加上视图宽度都已经移动到了左侧
      if (-distance > length + width) {
        distance = width; // 重置距离到初始位置
      }
      this.setData({
        marqueeDistance: distance
      });
    }, 20);
  },

  clearMarqueeInterval: function () { // 若定时器存在，清除定时器
    if (this.data.intervalId) {
      clearInterval(this.data.intervalId);
      this.data.intervalId = null;
    }
  },



  onReady: function() {
    // 页面渲染完成
  },
  onHide: function() {
    // 页面隐藏
  this.clearMarqueeInterval();
  },
  onUnload: function() {
  this.clearMarqueeInterval();
    // 页面关闭
  },
  getCoupon(e) {
    let couponId = e.currentTarget.dataset.index
    util.request(api.CouponReceive, {
      couponId: couponId
    }, 'POST').then(res => {
      if (res.errno === 0) {
        wx.showToast({
          title: "领取成功"
        })
      }
      else{
        util.showErrorToast(res.errmsg);
      }
    })
  },
})
